package controllers;

import helpers.CrawlerHelper;
import helpers.UrlHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.MetaSeoModel;

import systems.ConfigSystem;

import entities.KeywordRanking;
import entities.MetaSeo;
import entities.SiteConfig;

import models.KeywordRankingModel;

public class KeywordRankingServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		String name = (String) request.getParameter("q");
		
		KeywordRankingModel keywordModel = KeywordRankingModel.getInstance();
		KeywordRanking keyword = null;
		if (name != null && UrlHelper.checkDomain(name)) {
			name = UrlHelper.getMainDomain(name);
			keyword = keywordModel.get(name);
			if (keyword == null) {
				keyword = new KeywordRanking();
				keyword.setDomain(name);
				keyword = CrawlerHelper.getKeywordRanking(keyword);
				keywordModel.insert(keyword);
			}
		}
		
		//Set seo content
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get("keyword");
		
		request.setAttribute("name", name);
		request.setAttribute("keyword", keyword);
		request.setAttribute("metaseo", metaseo);
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/keyword_ranking.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
